import 'dart:convert' as convert;

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/login/login_area_code_dialog.dart';
import 'package:flutter_syt/domain/login/widgets/login_forget_input_decorator.dart';
import 'package:flutter_syt/domain/login/widgets/login_phone_form_field.dart';
import 'package:flutter_syt/domain/login/widgets/popup_route.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_other.dart';

import '../../../global_easy_loading.dart';

// class PhoneWithAreaCodeEntity {
//   String phone = '';
//   String areaCode = '86';
//   PhoneWithAreaCodeEntity();

//   factory PhoneWithAreaCodeEntity.create(String phone,
//       {String areaCode = '86'}) {
//     return PhoneWithAreaCodeEntity()
//       ..phone = phone
//       ..areaCode = areaCode;
//   }
//   Map<String, dynamic> get jsonValue {
//     var result = Map<String, dynamic>();
//     result["phone"] = this.phone;
//     result["areaCode"] = this.areaCode;
//     return result;
//   }
// }

class LoginForgetPhoneFormField extends StatefulWidget {
  final FormFieldSetter<PhoneWithAreaCodeEntity>? onSaved;
  final TextEditingController? controller;
  final FocusNode? focusNode;
  final void Function()? onEditingComplete;
  final Function(String)? onChanged;

  const LoginForgetPhoneFormField({
    Key? key,
    this.onSaved,
    this.controller,
    this.onEditingComplete,
    this.onChanged,
    this.focusNode,
  }) : super(key: key);

  @override
  _LoginForgetPhoneFormFieldState createState() =>
      _LoginForgetPhoneFormFieldState();
}

class _LoginForgetPhoneFormFieldState extends State<LoginForgetPhoneFormField> {
  String phone = '';
  String areaCode = '86';

  @override
  void initState() {
    super.initState();
    String cachePhone = appContext.storage.getString("login_phone") ?? '';
    String cachePhoneArea = appContext.storage.getString('login_area') ?? '';
    if (cachePhone != '') {
      Map<String, dynamic> map = convert.json.decode(cachePhone);
      setState(() {
        phone = map['phone'];
        if (cachePhoneArea != '') {
          areaCode = cachePhoneArea;
        } else {
          areaCode = map['areaCode'];
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextFormField(
        enableInteractiveSelection: false,
        initialValue: phone,
        inputFormatters: [
          FilteringTextInputFormatter.deny(appContext.emojiRegexp)
        ],
        controller: widget.controller,
        autofocus: false,
        focusNode: widget.focusNode,
        maxLength: areaCode == '86' ? 11 : 25,
        style: TextStyle(
          color: Colors.black,
          fontSize: 16,
          height: 1.5,
          fontWeight: FontWeight.bold,
        ),
        cursorColor: ThemeColor.primaryColor,
        onEditingComplete: widget.onEditingComplete,
        onChanged: widget.onChanged,
        decoration: LoginForgetInputDecoration(
          // //  hintText: hintText,
          // // prefixIcon: prefixIcon,
          // prefixIconConstraints: BoxConstraints(minWidth: 0, minHeight: 0),
          // // suffixIcon: suffixIcon,
          // counterText: '',
          // hintStyle: TextStyle(
          //   color: Colors.black.withOpacity(0.4),
          //   fontSize: 16,
          // ),
          // focusColor: Colors.white,
          // contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
          // enabledBorder: OutlineInputBorder(
          //   borderRadius: BorderRadius.all(
          //     Radius.circular(8),
          //   ),
          //   borderSide: BorderSide(color: Colors.transparent),
          // ),
          // focusedBorder: OutlineInputBorder(
          //   borderRadius: BorderRadius.all(
          //     Radius.circular(8),
          //   ),
          //   borderSide: BorderSide(color: Colors.transparent),
          // ),
          // errorBorder: InputBorder.none,
          // errorStyle: TextStyle(height: 0),
          // focusedErrorBorder: InputBorder.none,

          // filled: true,
          hintText: S.of(context).enter_mobile_mumber,

          prefixIcon: Container(
            padding: EdgeInsets.only(
              top: 0,
              left: 10,
              right: 5,
              bottom: 0,
            ),
            margin: EdgeInsets.only(right: 10),
            decoration: BoxDecoration(
              border: Border(
                right: BorderSide(color: Colors.black.withOpacity(0.8)),
              ),
            ),
            child: GestureDetector(
              onTap: ClickUtils.debounce(() {
                showAreaAlert();
              }),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    '+$areaCode',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.black.withOpacity(0.8),
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Icon(
                    Icons.arrow_drop_down,
                    color: Colors.black.withOpacity(0.8),
                  ),
                ],
              ),
            ),
          ),
        ),
        validator: (val) {
          if (areaCode == '86') {
            if (!RegexUtil.isMobileSimple(val!)) {
              customShowToast(S.of(context).enter_valid_phone);
              return '';
            }
          } else if (!RegexUtil.matches('^\\d{6,25}\$', val!)) {
            customShowToast(S.of(context).enter_valid_phone);
            return '';
          }
          return null;
        },
        onSaved: (val) {
          PhoneWithAreaCodeEntity _phone = PhoneWithAreaCodeEntity.create(
            val!,
            areaCode: areaCode,
          );
          var value = convert.json.encode(_phone.jsonValue);
          appContext.storage.setString("login_phone", value);
          widget.onSaved!(_phone);
        },
        obscureText: false,
        keyboardType: TextInputType.phone,
      ),
    );
  }

  void showAreaAlert() async {
    List<AreaCodeData> list = [];
    try {
      list = await API.shared.login.areaList();
      list.sort((left, right) => left.pinyinName.compareTo(right.pinyinName));
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowToast(e.message);
      // } else {
      //   customShowToast(S().network_error);
      // }
      return;
    }
    var titleKey = '';
    for (int i = 0; i < list.length; i++) {
      var item = list[i];
      var title = '';
      try {
        title = item.pinyinName.substring(0, 1).toUpperCase();
      } catch (e) {
        title = '#';
      }
      if (titleKey != title) {
        titleKey = title;
        item.firstName = titleKey;
      }
    }
    Navigator.push(
        context,
        NNPopupRoute(
            needSafe: true,
            alignment: Alignment.bottomCenter,
            onClick: () {
              Navigator.of(context).pop();
            },
            child: LoginAreaCodePage(
                onClick: (AreaCodeData item) {
                  setState(() {
                    areaCode = item.areaCode;
                  });
                },
                data: list)));
  }
}
